<?php
/* 
* @Author: LDF QQ 47121862
* @Date:   2014-05-30 09:41:39
* @Last Modified by:   LDF QQ 47121862
* @Last Modified time: 2014-06-03 10:50:43
*/
Class CategoryModel extends Model{
	public $table='category';
	public $validate=array(
		array('cname','nonull','栏目名称不能为空',2,3)
	);
	public $auto=array(
		array('pic','pic','method',2,3)
	);
	//栏目图片处理
	public function pic(){
		if(!empty($_FILES['pic']['name'])){
			if(isset($_POST['oldpic'])) @unlink(ROOT_PATH.$_POST['oldpic']); //删除原有图片
			$u = new Upload();
			$info = $u->upload('pic');
			return $info[0]['path'];
		}
	}
	//添加栏目
	public function addCate(){
		if($this->create()){
			$cid=$this->add();
			if($cid){
				//更新缓存
				$this->updateCache();
				return $cid;
			}else{
				$this->error='添加栏目失败！！';
				return 0;
			}
		}else{
			$this->error='验证错误';
			return 0;
		}
	}
	//修改栏目
	public function editCate(){
		if($this->create()){
			$id = $this->save();
			if($id){
				if($this->updateCache()){
					return $id;
				}else{
					$this->error = '更新缓存失败。。。';
					return false;
				}
			}else{
				$this->error = '修改失败...';
				return false;
			}
		}else{
			return false;
		}
	}
	//删除栏目
	public function delCate(){
		$cid = Q('cid',0,'intval');
		$data=$this->find($cid);
		if($this->where(array('pid'=>$cid))->find()){
			$this->error = '请先删除子栏目';
			return false;
		}
		if($this->del($cid)){
			if($this->updateCache()){
				//删除图片
				if($data['pic']) @unlink(ROOT_PATH.$data['pic']);
				return true;
			}else{
				$this->error = '更新缓存失败。。。';
				return false;
			}
		}else{
			$this->error = '删除失败...';
			return false;
		}
	}
	//更新缓存
	public function updateCache(){
		$cate = $this->order('cid DESC')->getField('cid,pid,cname,pic,hits,keywords,description,type,url');
		$cate=Data::tree($cate,'cname');
		return cache('category',$cate);
	}
}